package com.graduation.springbootinit.controller;

import com.graduation.springbootinit.common.BaseResponse;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.common.ResultUtils;
import com.graduation.springbootinit.exception.BusinessException;
import com.graduation.springbootinit.model.dto.conversation.ConversationRequest;
import com.graduation.springbootinit.model.dto.conversation.CreateConversationRequest;
import com.graduation.springbootinit.model.dto.conversation.SendMessageRequest;
import com.graduation.springbootinit.model.entity.ShopPart.Conversation;
import com.graduation.springbootinit.model.entity.ShopPart.Message;
import com.graduation.springbootinit.model.entity.User;
import com.graduation.springbootinit.model.vo.ShopPartVo.ConversationVO;
import com.graduation.springbootinit.model.vo.ShopPartVo.MessageVO;
import com.graduation.springbootinit.service.ConversationService;
import com.graduation.springbootinit.service.MessageService;
import com.graduation.springbootinit.service.StoreService;
import com.graduation.springbootinit.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/conversation")
public class ConversationController {

    @Resource
    private ConversationService conversationService;

    @Resource
    private MessageService messageService;

    @Resource
    private UserService userService;

    @Resource
    private StoreService storeService;

    private static final String CURRENT_STORE_STATE = "current_store_state";

    /**
     * 用户获取与商铺的对话列表
     */
    @PostMapping("/user/list")
    public BaseResponse<List<ConversationVO>> listUserConversations(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        List<Conversation> conversations = conversationService.getUserConversations(loginUser.getId(), false);
        
        List<ConversationVO> conversationVOList = conversations.stream().map(conversation -> {
            ConversationVO conversationVO = new ConversationVO();
            BeanUtils.copyProperties(conversation, conversationVO);
            // 只设置未读数，不获取消息
            conversationVO.setUnreadCount(conversation.getUserUnreadCount());
            return conversationVO;
        }).collect(Collectors.toList());
        
        return ResultUtils.success(conversationVOList);
    }

    /**
     * 商家获取与用户的对话列表
     */
    @PostMapping("/store/list")
    public BaseResponse<List<ConversationVO>> listStoreConversations(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (!userService.isStoreMerchant(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "非商家用户");
        }
        
        // 从Session中获取当前管理的商铺ID
        Long storeId = (Long) request.getSession().getAttribute(CURRENT_STORE_STATE);
        if (storeId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "请先选择要管理的商铺");
        }
        
        // 使用商铺ID获取会话列表
        List<Conversation> conversations = conversationService.getUserConversations(storeId, true);
        
        List<ConversationVO> conversationVOList = conversations.stream().map(conversation -> {
            ConversationVO conversationVO = new ConversationVO();
            BeanUtils.copyProperties(conversation, conversationVO);
            conversationVO.setUnreadCount(conversation.getStoreUnreadCount());
            return conversationVO;
        }).collect(Collectors.toList());
        
        return ResultUtils.success(conversationVOList);
    }

    /**
     * 用户获取对话详情
     */
    @PostMapping("/user/detail")
    public BaseResponse<ConversationVO> getUserConversationDetail(@RequestBody ConversationRequest request,
                                                                HttpServletRequest httpRequest) {
        User loginUser = userService.getLoginUser(httpRequest);
        Conversation conversation = conversationService.getById(request.getConversationId());
        
        if (conversation == null || !conversation.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权访问该对话");
        }
        
        // 获取消息历史
        List<Message> messages = messageService.getHistoryMessages(conversation.getId(), 20, null);
        // 分类消息
        List<Message> userMsgs = messages.stream()
            .filter(msg -> msg.getSenderType() == 0)
            .collect(Collectors.toList());
        List<Message> storeMsgs = messages.stream()
            .filter(msg -> msg.getSenderType() == 1)
            .collect(Collectors.toList());
        
        // 标记消息和会话为已读
        messageService.markMessagesAsRead(conversation.getId(), 0);  // 标记消息已读
        conversationService.markAsRead(conversation.getId(), false); // 标记会话已读
        
        ConversationVO conversationVO = new ConversationVO();
        BeanUtils.copyProperties(conversation, conversationVO);
        conversationVO.setUserMessages(userMsgs.stream()
            .map(this::convertToMessageVO)
            .collect(Collectors.toList()));
        conversationVO.setStoreMessages(storeMsgs.stream()
            .map(this::convertToMessageVO)
            .collect(Collectors.toList()));
        
        return ResultUtils.success(conversationVO);
    }

    /**
     * 商家获取对话详情
     */
    @PostMapping("/store/detail")
    public BaseResponse<ConversationVO> getStoreConversationDetail(@RequestBody ConversationRequest request,
                                                                 HttpServletRequest httpRequest) {
        User loginUser = userService.getLoginUser(httpRequest);
        if (!userService.isStoreMerchant(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "非商家用户");
        }
        
        // 从Session中获取当前管理的商铺ID
        Long storeId = (Long) httpRequest.getSession().getAttribute(CURRENT_STORE_STATE);
        if (storeId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "请先选择要管理的商铺");
        }
        
        Conversation conversation = conversationService.getById(request.getConversationId());
        if (conversation == null || !conversation.getStoreId().equals(storeId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权访问该对话");
        }
        
        // 获取消息历史
        List<Message> messages = messageService.getHistoryMessages(conversation.getId(), 20, null);
        // 分类消息
        List<Message> userMsgs = messages.stream()
            .filter(msg -> msg.getSenderType() == 0)
            .collect(Collectors.toList());
        List<Message> storeMsgs = messages.stream()
            .filter(msg -> msg.getSenderType() == 1)
            .collect(Collectors.toList());
        
        // 标记消息和会话为已读
        messageService.markMessagesAsRead(conversation.getId(), 1);  // 标记消息已读
        conversationService.markAsRead(conversation.getId(), true);  // 标记会话已读
        
        ConversationVO conversationVO = new ConversationVO();
        BeanUtils.copyProperties(conversation, conversationVO);
        conversationVO.setUserMessages(userMsgs.stream()
            .map(this::convertToMessageVO)
            .collect(Collectors.toList()));
        conversationVO.setStoreMessages(storeMsgs.stream()
            .map(this::convertToMessageVO)
            .collect(Collectors.toList()));
        
        return ResultUtils.success(conversationVO);
    }

    /**
     * 用户发送消息给商家
     */
    @PostMapping("/user/send")
    public BaseResponse<MessageVO> sendUserMessage(@RequestBody SendMessageRequest request, 
                                                 HttpServletRequest httpRequest) {
        User loginUser = userService.getLoginUser(httpRequest);
        
        // 验证对话存在且属于当前用户
        Conversation conversation = conversationService.getById(request.getConversationId());
        if (conversation == null || !conversation.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权访问该对话");
        }
        
        Message message = messageService.createMessage(
                request.getConversationId(),
                loginUser.getId(),
                0,
                request.getContent(),
                0
        );
        
        // 更新会话状态
        conversationService.updateLastMessage(request.getConversationId(), request.getContent(), 0);
        conversationService.incrementUnreadCount(request.getConversationId(), true);
        
        return ResultUtils.success(convertToMessageVO(message));
    }

    /**
     * 商家发送消息给用户
     */
    @PostMapping("/store/send")
    public BaseResponse<MessageVO> sendStoreMessage(@RequestBody SendMessageRequest request, 
                                                  HttpServletRequest httpRequest) {
        User loginUser = userService.getLoginUser(httpRequest);
        if (!userService.isStoreMerchant(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "非商家用户");
        }
        
        // 从Session中获取当前管理的商铺ID
        Long storeId = (Long) httpRequest.getSession().getAttribute(CURRENT_STORE_STATE);
        if (storeId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "请先选择要管理的商铺");
        }
        
        // 验证对话存在且属于当前商铺
        Conversation conversation = conversationService.getById(request.getConversationId());
        if (conversation == null || !conversation.getStoreId().equals(storeId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权访问该对话");
        }
        
        Message message = messageService.createMessage(
                request.getConversationId(),
                loginUser.getId(),
                1,
                request.getContent(),
                0
        );
        
        // 更新会话状态
        conversationService.updateLastMessage(request.getConversationId(), request.getContent(), 1);
        conversationService.incrementUnreadCount(request.getConversationId(), false);
        
        return ResultUtils.success(convertToMessageVO(message));
    }

    /**
     * 用户创建与商铺的对话
     */
    @PostMapping("/user/start")
    public BaseResponse<ConversationVO> startUserConversation(@RequestBody CreateConversationRequest request, 
                                                            HttpServletRequest httpRequest) {
        User loginUser = userService.getLoginUser(httpRequest);
        String storeName = storeService.getStoreNameById(request.getStoreId());
        
        // 获取或创建对话，包含消息详情
        Conversation conversation = conversationService.getOrCreateConversation(
                loginUser.getId(),
                loginUser.getUserName(),
                request.getStoreId(),
                storeName
        );
        
        // 转换为VO对象
        ConversationVO conversationVO = new ConversationVO();
        BeanUtils.copyProperties(conversation, conversationVO);
        
        if (conversation.getUserMessages() != null) {
            conversationVO.setUserMessages(conversation.getUserMessages().stream()
                .map(this::convertToMessageVO)
                .collect(Collectors.toList()));
        }
        if (conversation.getStoreMessages() != null) {
            conversationVO.setStoreMessages(conversation.getStoreMessages().stream()
                .map(this::convertToMessageVO)
                .collect(Collectors.toList()));
        }
        
        return ResultUtils.success(conversationVO);
    }
    
    /**
     * 转换Message为MessageVO
     */
    private MessageVO convertToMessageVO(Message message) {
        MessageVO messageVO = new MessageVO();
        BeanUtils.copyProperties(message, messageVO);
        return messageVO;
    }
}